<template>
  <div class="chart-wrap">
    <h3 class="title">📈 投票结果图表</h3>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  candidates: { type: Array, default: () => [] }
});

const chartRef = ref(null);
let chartInstance = null;

function renderChart() {
  if (!chartRef.value) return;

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      top: 32,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.candidates.map(c => c.name),
      axisLabel: { rotate: 26, color: '#25355a', fontWeight: 500 }
    },
    yAxis: {
      type: 'value',
      name: '票数',
      minInterval: 1,
      axisLabel: { color: '#25355a', fontWeight: 500 },
      splitLine: { lineStyle: { color: '#e5e9ef' } }
    },
    series: [
      {
        data: props.candidates.map(c => c.voteCount),
        type: 'bar',
        label: { show: true, position: 'top', color: '#27468a', fontWeight: 600 },
        itemStyle: {
          borderRadius: [5, 5, 0, 0],
          color: '#27468a'
        }
      }
    ]
  };

  chartInstance.setOption(option);
}

onMounted(renderChart);
watch(() => props.candidates, renderChart, { deep: true });
onUnmounted(() => {
  if (chartInstance) chartInstance.dispose();
});
</script>

<style scoped>
.chart-wrap {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e5e9ef;
  box-shadow: 0 2px 10px rgba(50,60,90,0.08);
  padding: 28px 12px 18px 12px;
  margin-top: 22px;
}

.title {
  font-size: 1.11rem;
  font-weight: 600;
  color: #25355a;
  margin-bottom: 20px;
  text-align: center;
  letter-spacing: 0.01em;
}

.chart {
  width: 100%;
  height: 300px;
  min-height: 200px;
}
@media (max-width: 640px) {
  .chart-wrap { padding: 12px 2vw 12px 2vw; margin-top: 10px; }
  .chart { height: 210px; }
  .title { font-size: 1rem; margin-bottom: 13px; }
}
</style>
